package com.newly.common.core.utils;

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;

/**
 * Created by liuleyi on 2019/1/30 3:35 PM
 */
public class CacheManager {

    private static class CacheManagerHolder {
        private final static CacheManager cacheInstance = new CacheManager();
    }

    public static CacheManager getInstance() {
        return CacheManagerHolder.cacheInstance;
    }

    private Cache<String, String> cache;

    private Logger logger = LoggerFactory.getLogger(CacheManager.class);

    private static final long CHECK_PHONE_TIMES = 180;  //手机验证码过期时间 3分钟
    private static final long CHECK_EMAIL_TIMES = 300;  //邮箱验证码过期时间 5分钟

    private CacheManager() {
        cache = Caffeine.newBuilder()
                .expireAfterWrite(CHECK_EMAIL_TIMES, TimeUnit.SECONDS)
                .initialCapacity(100).build();
    }

    public void putPhoneCaptcha(String phone, String msg) {
        cache.put(phone, msg);
    }

    /**
     * 把邮箱验证码加入缓存
     *
     * @param email
     * @param msg
     */
    public void putEmailCaptcha(String email, String msg) {
        cache.put(email, msg);
    }

    public String getPhoneCaptcha(String phone) {
        return cache.getIfPresent(phone);
    }

    /**
     * 获取邮箱验证码缓存
     *
     * @param email
     * @return
     */
    public String getEmailCaptcha(String email) {
        return cache.getIfPresent(email);
    }

    /**
     * 删除值
     *
     * @param key
     */
    public void deleteCaptcha(String key) {
        cache.invalidate(key);
    }
}
